﻿using Newtonsoft.Json;
using System.Data;
using System.Text;

namespace ExcelExport
{
    public class GenerateLua
    {
        private StringBuilder luaBuilder = new StringBuilder();

        private void AddHeadCode()
        {
            luaBuilder.Append("return { ");
            luaBuilder.Append(Util.NewLine);
        }

        public void WriteToFile(string className, List<TableField> fieldList, DataTable dt)
        {
            luaBuilder.Clear();
            AddHeadCode();

            int rowsCount = dt.Rows.Count;
            int columnsCount = dt.Columns.Count;
            //遍历数据
            for (int i = 0; i < rowsCount; i++)
            {
                luaBuilder.Append("\t{");
                for (int j = 0; j < columnsCount; j++)
                {
                    TableField field = fieldList[j];
                    object o = dt.Rows[i][j];
                    string objectStr = o.ToString();
                    luaCode(field, objectStr);
                }
                NewLine(i >= rowsCount - 1);
            }
            CreateLuaFile(className);
        }

        private void luaCode(TableField field, string str)
        {
            switch (field.fieldType)
            {
                case TableType.BYTE:
                case TableType.SHORT:
                case TableType.INT:
                case TableType.ULONG:
                case TableType.FLOAT:
                    AddLuaData(field.filedName, str);
                    break;
                case TableType.BOOL:
                    if (str.Equals("0"))
                    {
                        str = "false";
                    }
                    if (str.Equals("1"))
                    {
                        str = "true";
                    }
                    AddLuaData(field.filedName, str);
                    break;
                case TableType.STRING:
                    str = str.Replace("\n", "");
                    str = JsonConvert.SerializeObject(str);
                    AddLuaData(field.filedName, str);
                    break;
            }
        }

        private void AddLuaData(string fieldName, object val)
        {
            luaBuilder.Append(" " + fieldName);
            luaBuilder.Append(" = ");
            luaBuilder.Append(val);
            luaBuilder.Append(",");
        }

        public void CreateLuaFile(string className)
        {
            Utility.WriteFile(Util.dirOutLua + "/" + className + ".lua", luaBuilder.ToString());
        }

        private void NewLine(bool isLastLine)
        {
            luaBuilder.Remove(luaBuilder.Length - 1, 1);
            luaBuilder.Append("},");
            if (isLastLine)
            {
                luaBuilder.Remove(luaBuilder.Length - 1, 1);
                luaBuilder.Append("\n}");
            }
            else
            {
                luaBuilder.Append("\n");
            }
        }

    }
}
